<template>
  <div class="app-container">
    <splitpanes class="default-theme">
      <!--用户数据-->
      <pane size="16">
        <el-col style="height: 100%">
          <div class="head-container">
            <el-input v-model="userName" placeholder="请输入账号" clearable prefix-icon="el-icon-search" style="margin-bottom: 20px;width: 50%"  @keyup.enter.native="handleUserQuery"/>
            <el-input v-model="nickName" placeholder="请输入昵称" clearable prefix-icon="el-icon-search" style="width: 50%" @keyup.enter.native="handleUserQuery"/>
            <el-button type="primary" icon="el-icon-search" @click="handleUserQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="resetUserQuery">重置</el-button>
          </div>
          <div style="height: 90%">
            <el-table v-loading="userLoading" :data="userList" highlight-current-row @current-change="handleCurrentChange" >
              <el-table-column label="账号" align="center" prop="userName" />
              <el-table-column label="昵称" align="center" prop="nickName" />
            </el-table>
          </div>
        </el-col>
      </pane>
      <!--订单数据-->
      <pane>
        <el-col size="84" style="height: 100%">
          <el-form :model="queryOrderParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="系统单号" prop="sid">
              <el-input
                v-model="queryOrderParams.sid"
                placeholder="请输入系统单号"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleOrderQuery"
              >
                <el-button slot="append" icon="el-icon-edit-outline" @click="handleOpenDialog('sid')"/>
              </el-input>
            </el-form-item>
            <el-form-item label="平台单号" prop="tid">
              <el-input
                v-model="queryOrderParams.tid"
                placeholder="请输入平台单号"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleOrderQuery"
              >
                <el-button slot="append" icon="el-icon-edit-outline" @click="handleOpenDialog('tid')"/>
              </el-input>
            </el-form-item>
            <el-form-item label="快递单号" prop="outSid">
              <el-input
                v-model="queryOrderParams.outSid"
                placeholder="请输入快递单号"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleOrderQuery"
              >
                <el-button slot="append" icon="el-icon-edit-outline" @click="handleOpenDialog('outSid')"/>
              </el-input>
            </el-form-item>
            <el-form-item label="内部单号" prop="shortId">
              <el-input
                v-model="queryOrderParams.shortId"
                placeholder="请输入内部单号"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleOrderQuery"
              >
                <el-button slot="append" icon="el-icon-edit-outline" @click="handleOpenDialog('shortId')"/>
              </el-input>
            </el-form-item>
            <el-form-item label="四合一" prop="conditions">
              <el-input
                v-model="queryOrderParams.conditions"
                placeholder="系统单号/内部单号/平台单号/快递单号"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleOrderQuery"
              />
            </el-form-item>
            <el-form-item label="店铺名称" prop="shopName">
              <el-input
                v-model="queryOrderParams.shopName"
                placeholder="请输入店铺名称"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleOrderQuery"
              />
            </el-form-item>
            <el-form-item label="付款时间" prop="payTime">
              <el-date-picker clearable style="width: 240px"
                              value-format="timestamp"
                              type="datetimerange"
                              range-separator="-"
                              start-placeholder="开始时间"
                              end-placeholder="结束时间"
                              @keyup.enter.native="handleOrderQuery"
                              v-model="payTimeRange"/>
            </el-form-item>
            <el-form-item label="事业部" prop="buType">
              <el-select v-model="queryOrderParams.buType" placeholder="请选则事业部" clearable style="width: 240px" @keyup.enter.native="handleOrderQuery">
                <el-option label="3C事业部" value="0" />
                <el-option label="海报事业部" value="1" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="handleOrderQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" @click="resetOrderQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <el-row :gutter="10" class="mb8" ref="toolbar">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                :disabled="multiple"
                icon="el-icon-plus"
                v-hasPermi="['business:ordersStatus:selectAllocation']"
                @click="handleAllocation"
              >勾选分配</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                :disabled="single"
                icon="el-icon-plus"
                v-hasPermi="['business:ordersStatus:batchAllocation']"
                @click="handleBatchAllocation"
              >批量分配</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getOrderList" ></right-toolbar>
          </el-row>
          <div ref="divTable" style="height: calc(100vh - 300px)">
            <el-table ref="numberOrdersInfo" v-loading="orderLoading" :data="orderList" @selection-change="handleSelectionChange" row-key="sid">
              <el-table-column type="selection" width="55" align="center" :reserve-selection="true"/>
              <el-table-column label="序号" align="center" width="50">
                <template slot-scope="scope">
                  {{ (queryOrderParams.pageNum - 1) * queryOrderParams.pageSize + scope.$index + 1 }}
                </template>
              </el-table-column>
              <el-table-column label="详情图片" align="center" prop="detailPics">
                <template v-slot="scope">
                  <div style="display: flex; flex-wrap: wrap; gap: 5px; justify-content: center;">
                    <template v-if="scope.row.detailPics">
                      <template v-for="(pic, index) in scope.row.detailPics.split(',')">
                        <image-preview
                          v-if="pic.trim()"
                          :key="index"
                          :src="pic.trim()"
                          style="width: 80px; height: 80px; object-fit: cover;"
                        />
                      </template>
                    </template>
                    <span v-else>无图片</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="店铺名称" align="center" prop="shopName"/>
              <el-table-column label="系统单号" align="center" prop="sid" />
              <el-table-column label="平台单号" align="center" prop="tid" />
              <el-table-column label="内部单号" align="center" prop="shortId" />
              <el-table-column label="快递单号" align="center" prop="outSid" />
              <el-table-column label="付款时间" align="center" prop="payTime" width="140">
                <template v-slot="scope">
                  {{$parseTime(scope.row.payTime, '{y}-{m}-{d} {h}:{i}:{s}')}}
                </template>
              </el-table-column>
              <el-table-column label="卖家备注" align="center" prop="mergeList">
                <template v-slot="scope">
                  <div v-if="scope.row.mergeList && scope.row.mergeList.length > 0">
                    <template v-for="(item, index) in scope.row.mergeList">
                      <div v-if="item && item.sellerMemo" :key="index" style="display: flex; align-items: center; justify-content: center;">
                        <el-tooltip
                          effect="dark"
                          :content="item.sellerMemo"
                          placement="top"
                          popper-class="custom-tooltip"
                        >
                          <el-icon class="el-icon-s-comment" style="font-size: 20px;color: #189f15" />
                        </el-tooltip>
                      </div>
                    </template>
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <div class="table-footer">
              <div class="selected-count" v-show="ids.length > 0">
                已勾选：{{ ids.length }} 条数据
              </div>
              <div class="pagination-wrapper">
                <pagination
                  v-show="total>0"
                  :total="total"
                  :pageSizes= [50,100,150,200]
                  :page.sync="queryOrderParams.pageNum"
                  :limit.sync="queryOrderParams.pageSize"
                  @pagination="getOrderList"
                />
              </div>
            </div>
          </div>
        </el-col>
      </pane>
    </splitpanes>

    <el-dialog title="批量分配" :visible.sync="batchOpen" width="500px" append-to-body>
      <span>分配给：{{ this.userInfo? this.userInfo.nickName : '' }}</span>
      <el-input type="textarea" :rows="10" placeholder="请输入平台单号，多个用英文逗号隔开" style="margin-top: 5px" v-model="dialogInput" />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleBatchSubmit">确 定</el-button>
        <el-button @click="batchOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="批量添加" :visible.sync="open" width="500px" append-to-body>
      <el-input type="textarea" :rows="10" placeholder="请输入系统单号/平台单号/快递单号/内部单号，多个用英文逗号隔开" v-model="dialogInput" />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleBatchConfirm">确 定</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUser } from "@/api/system/user";
import {getUndistributedOrder} from "@/api/business/ordersMain"
import { checkTidIsUnique, getOrderStatusInfo, updateOrderStatus} from "@/api/business/ordersStatus"
import ResizeMixin from "@/layout/mixin/ResizeHandler";
import {Pane, Splitpanes} from "splitpanes";
import "splitpanes/dist/splitpanes.css";

export default {
  name: "OrderNumber",
  components: { Pane, Splitpanes },
  mixins: [ResizeMixin],
  data() {
    return {
      // 表格高度
      divHeight: 0,
      // 遮罩层
      userLoading: true,
      // 订单遮罩层
      orderLoading: true,
      userName: '',
      nickName: '',
      // 用户列表
      userList: [],
      // 订单列表
      orderList: [],
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // 非单个禁用
      single: true,
      // 选中的用户id
      userInfo: null,
      // 数据总量
      total: 0,
      // 订单查询参数
      queryOrderParams: {
        pageNum: 0,
        pageSize: 50,
        shopName: null,
        conditions: null,
        allocateType: '0',
      },
      // 滚动条是否禁用
      disabled: false,
      // 显示搜索条件
      showSearch: true,
      // 是否显示弹出层
      open: false,
      // 待分配的订单sid
      allocationSids: "",
      // 存储 dialog 中输入的内容
      dialogInput: '',
      // 当前点击的 input 类型（sid、tid、outSid、shortId）
      currentInputType: '',
      // 勾选的信息
      selectedData: [],
      // 批量分配弹出框
      batchOpen: false,
      // 付款时间查询
      payTimeRange: [],
    }
  },
  created() {
    this.getUserList();
    this.getOrderList();
  },
  methods: {
    /** 查询用户列表 */
    getUserList() {
      this.userLoading = true;
      listUser({userName: this.userName, nickName: this.nickName, pageSize: 1000}).then(response => {
        this.userList = response.rows;
        this.userLoading = false;
      });
    },
    /** 获取未分配的订单 */
    getOrderList() {
      this.orderLoading = true;
      getUndistributedOrder(this.$addDateRange(this.queryOrderParams, this.payTimeRange, 'PayTime')).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.orderLoading = false;
      });
    },
    /** 用户搜索操作 */
    handleUserQuery() {
      this.getUserList();
    },
    /** 用户重置操作 */
    resetUserQuery(){
      this.userName = null;
      this.nickName = null;
      this.getUserList();
    },
    /** 订单搜索按钮操作 */
    handleOrderQuery(){
      this.queryOrderParams.pageNum = 1;
      this.getOrderList();
    },
    /** 订单列表选中 */
    handleSelectionChange(selection) {
      const userInfo = this.userInfo;
      this.ids = selection.map(item => item.id)
      this.selectedData = selection.map(item => ({
        ...item,
        userId: userInfo?.userId || null,
        deptId: userInfo?.deptId || null,
        orderStatus: 'MANUAL_DESIGN',
        content: '订单分配给' +  (userInfo?.nickName || null),
      }));
      this.multiple = (!selection.length || this.userInfo === null);
    },
    /** 用户列表选中 */
    handleCurrentChange(val){
      this.userInfo = val;
      this.single = false;
      this.ids = [];
      this.selectedData = [];

      // 清空表格中的选中状态
      this.$nextTick(() => {
        this.$refs.numberOrdersInfo?.clearSelection();
      })
      this.queryOrderParams.pageNum = 1;
      this.getOrderList();
    },
    /** 重置按钮操作 */
    resetOrderQuery() {
      this.payTimeRange = [];
      this.$resetForm("queryForm");
      this.handleOrderQuery();
    },
    /** 打开弹出框 */
    handleOpenDialog(type){
      this.currentInputType = type; // 记录当前 input 类型
      // 将当前 input 的内容赋值给 dialogInput
      switch (type) {
        case 'sid':
          this.dialogInput = this.queryOrderParams.sid || '';
          break;
        case 'tid':
          this.dialogInput = this.queryOrderParams.tid || '';
          break;
        case 'outSid':
          this.dialogInput = this.queryOrderParams.outSid || '';
          break;
        case 'shortId':
          this.dialogInput = this.queryOrderParams.shortId || '';
          break;
        default:
          this.dialogInput = '';
          break;
      }
      this.open = true; // 打开 dialog
    },
    /** 弹出框确认 */
    handleBatchConfirm() {
      if (this.dialogInput) {
        // 根据当前 input 类型，将 dialog 中的内容赋值给对应的 queryParams 字段
        switch (this.currentInputType) {
          case 'sid':
            this.queryOrderParams.sid = this.dialogInput;
            break;
          case 'tid':
            this.queryOrderParams.tid = this.dialogInput;
            break;
          case 'outSid':
            this.queryOrderParams.outSid = this.dialogInput;
            break;
          case 'shortId':
            this.queryOrderParams.shortId = this.dialogInput;
            break;
          default:
            break;
        }
        this.open = false; // 关闭 dialog
      }
    },
    /** 勾选分配按钮 */
    handleAllocation(){
      this.selectedData.forEach(item => {
        item.accessTime = new Date().getTime();
      })
      updateOrderStatus(this.selectedData).then(res => {
        this.$modal.msgSuccess("批量分配成功");
        this.getOrderList();
        this.ids = [];
        this.selectedData = [];

        // 清空表格中的选中状态
        this.$nextTick(() => {
          this.$refs.numberOrdersInfo?.clearSelection();
        })
      })
    },
    /** 批量分配 */
    handleBatchAllocation(){
      this.dialogInput = null;
      this.batchOpen = true;
    },

    /** 批量分配确定按钮 */
    handleBatchSubmit(){
      // 单号去重
      const ordersStatus = [...new Set(this.dialogInput.split(',').map(item => {
        return {
          tid: item.trim()
        };
      }))];

      checkTidIsUnique(ordersStatus, 'MANUAL_SERVICE').then(res => {
        const duplicateTids = res.data || [];
        const data = duplicateTids.join(',');

        // 如果有重复单号
        if (duplicateTids.length > 0) {
          navigator.clipboard.writeText(data);
          this.$modal.msgWarning('重复平台单号，已忽略分配；已复制到剪贴板');

          // 过滤掉重复的 tid
          const filteredOrders = ordersStatus.filter(
            item => !duplicateTids.includes(item.tid)
          );
          if (filteredOrders.length > 0) {
            this.submitOrders(filteredOrders, false);
          }
        } else {
          // 无重复时直接使用原数据
          this.submitOrders(ordersStatus);
        }
      });

    },
    /** 批量提交单号 */
    async submitOrders(ordersStatus, isMsg = true) {
      const userInfo = this.userInfo;
      // 等待补全信息接口完成
      const res = await getOrderStatusInfo(ordersStatus, 'MANUAL_SERVICE');
      if (res.data.length) {
        const enhancedData = res.data;
        enhancedData.forEach(item => {
          item.orderStatus = 'MANUAL_DESIGN';
          item.content= '订单分配给' +  (userInfo?.nickName || null);
          item.userId = userInfo?.userId || null;
          item.deptId = userInfo?.deptId || null;
          item.assignTime = new Date().getTime();
        });

        // 使用补全后的数据提交更新
        await updateOrderStatus(enhancedData, 'MANUAL_SERVICE');
      }
      // 统一处理成功状态
      this.batchOpen = false;
      if (isMsg) this.$modal.msgSuccess("匹配成功");
      this.getOrderList();
    }
  }
}

</script>

<style lang="scss" scoped>
/* 任务退回的背景色 */
::v-deep .el-table .warning-row td{
  background: #F56C6C!important;
}
.table-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
  padding: 8px 0;
}

.selected-count {
  font-size: 14px;
  color: #666;
}

.pagination-wrapper {
  text-align: right;
}
</style>
